package py.org.atom.seam;

import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.Messages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;

import py.org.atom.action.Authenticator;
import py.org.atom.ldap.Ldap;
import py.org.atom.seam.entity.BaseUser;
import py.org.atom.seam.util.SHA1;

@Stateless
@Name("authenticator")
public class AuthenticatorBean  implements Authenticator{

    @Logger private Log log;

    @In(create=true) @Out(scope=ScopeType.SESSION) 
    Identity identity;
    @In Credentials credentials;
    @In FacesMessages facesMessages;
    
    @PersistenceContext(unitName="atom")
    private EntityManager em;
    
    @SuppressWarnings("unchecked")
	public boolean authenticate()
    {
    	
        String msg = "";
        
        if("".equals(credentials.getUsername().trim())){
        	msg = Messages.instance().get("py.org.atom.msg.UserRequired");
        	this.facesMessages.add(Severity.WARN, msg);
        	return false;
        }
        
        if("".equals(credentials.getPassword().trim())){
        	msg = Messages.instance().get("py.org.atom.msg.PasswordRequired");
        	this.facesMessages.add(Severity.WARN, msg);
        	return false;
        }
        
        String usr = credentials.getUsername().trim();
        
        String query = "Select u From User u Where id = :username";
        
        List lu = this.em.createQuery(query)
        				.setParameter("username", usr)
        				.setMaxResults(1)
        				.getResultList();
        
        if(lu == null || lu.size() <= 0){
        	msg = Messages.instance().get("py.org.atom.msg.UserNotFound");
        	this.facesMessages.add(Severity.WARN, msg);
        	return false;
        }
       
        BaseUser u = (BaseUser) lu.get(0);
        
        if(u.getStatus() == null || u.getStatus().trim().equals("I")){
        	msg = Messages.instance().get("py.org.atom.msg.UserDisabled");
        	this.facesMessages.add(Severity.WARN, msg);
        	return false;        	
        }
        	
        boolean out = false;
        
        if(!u.getLdap().trim().equals("Y")){
        	out = this.simpleAuth(u);
        }else{
        	out = this.ldapAuth(u);
        }
        if(out){
			if(this.identity != null)
				this.identity.setUser(u);        	
        }
        
        return out;
    }	
	
    private boolean ldapAuth(BaseUser u){
    	
    	String pass = credentials.getPassword().trim();
    	boolean out = false;
    	try {
			out = Ldap.auth(u.getId(), pass);
		} catch (Exception e) {
        	this.facesMessages.add(Severity.ERROR, "" + e);			
		}
    	
    	return out;
    }
    
    private boolean simpleAuth(BaseUser u){
        try {
        	String pass = credentials.getPassword().trim();
        	
			String shaPwd = SHA1.getHash(pass);
			if(shaPwd.trim().equals(u.getPwd().trim())){
				return true;
			}else{
				String msg = Messages.instance().get("py.org.atom.msg.PasswordInvalid");
				this.facesMessages.add(Severity.WARN, msg);
			}
		} catch (NoSuchAlgorithmException e) {
			log.error("Error encripting password: ", e);
		}
        return false;    	
    }
    
}
